'''
Created on 23/09/2012

@author: Charles Murray
'''

import xml.etree.ElementTree as ET
from Container import *
from Model import *
#from Next import *
from Subtree import *
from Option import *

class Parser(object):
    '''
    classdocs
    '''

    linkList = []

    def __init__(self, filename):
        '''
        Constructor
        '''
        self.tree = ET.parse(filename)
        self.root = self.tree.getroot()
        #parse(root)
         
    """
    Goes through and parses the XML so that we can generate the model.
    """       
    def parse(self, root):        
        if not list(root):
            return self.tag(root)
        else:
            subtree = []
            for child in root:
                #print child
                subtree.append(self.parse(child))
            subtree = Subtree(subtree)
            return self.tag(root, subtree)
    
    """     
    Determines what the tag represents and creates the object based off that.
    """
    def tag(self, root, subtree=None):
        if root.tag == "container":
            attributes = root.attrib
            return Container(attributes["mapping"], attributes["start"], attributes["end"], attributes["id"], attributes["filler"], subtree)
            """
        elif root.tag == "next":
            attributes = root.attrib
            nextTag = Next(attributes["id"])
            self.linkList.append(nextTag)
            return nextTag
            """
        elif root.tag == "option":
            #print subtree
            attributes = root.attrib
            optionTag = Option(attributes["start"], attributes["id"], subtree, attributes["link"])
            self.linkList.append(optionTag)
            return optionTag
        elif root.tag == "model":
            attributes = root.attrib
            return Model(attributes["start"], attributes["end"], subtree)
           
           
    """
    Goes through all of the next items so that you can 
    connect them all to the Id defined.
    """     
    def linkTags(self, model):
        for nextTag in self.linkList:
            self.traverse(model, nextTag)
        return model
    """
    Goes through the model that has been generated and connects the next object to 
    the object with the id that it should be pointing to. At some point I will have 
    to make sure that we check for multiple of the same id.
    """        
    def traverse(self, model, nextTag):
        if not model.getSubtree():
            return nextTag
        for child in model.getSubtree():
            #print child
            if child.getId() == nextTag.getLinkAddr():
                nextTag.setLink(child)
            else:
                self.traverse(child, nextTag)
        return nextTag
            
    def getLinkList(self):
        return self.linkList
             
    
    def getRoot(self):
        return self.root
